#include "ftphandler.hpp"
#include <sstream>

using namespace com_oocl_riley;
using std::stringstream;

FtpHandler::FtpHandler(FtpPool &pool)
: _pool(pool) {
}

FtpHandler::~FtpHandler() {
}

DataCollection *FtpHandler::perform(string *uri)
{
    string url;
    DataCollection *data = new DataCollection;
    Connection *con =
            curl_easy_setopt(con, CURLOPT_VERBOSE, 1L);
    if (*uri != "")
        url = _pool.Host() + "/" + *uri;
    else
        url = _pool.Host();
    curl_easy_setopt(con, CURLOPT_URL, url.c_str());
    if (_pool.Usr() != "" && _pool.Pwd() != "")
        curl_easy_setopt(con, CURLOPT_USERPWD, (_pool.Usr() + ":" + _pool.Pwd()).c_str());
    if (_pool.Port() != "")
        curl_easy_setopt(con, CURLOPT_PORT, _pool.Port().c_str());
    curl_easy_setopt(con, CURLOPT_WRITEFUNCTION, write_fun);
    curl_easy_setopt(con, CURLOPT_WRITEDATA, data);
    curl_easy_perform(con);
    _pool.releaseConnection(con);
    return data;
}

size_t FtpHandler::write_fun(char * buff, size_t size, size_t nmenb, void * data) {
    DataCollection *out = static_cast<DataCollection*> (data);
    if (out) {
        stringstream strBuff;
        string line;
        strBuff.write(buff, size * nmenb);
        while (getline(strBuff, line)) {
            if (line.find("<DIR>") != string::npos)
                continue;
            if (line[line.size() - 1] == '\r')
                line.erase(line.size() - 1);
            stringstream sline;
            sline.write(line.c_str(), line.length());
            string date, time, fileName;
            int fSize;
            sline >> date >> time >> fSize;
            getline(sline, fileName);
            out->insert(fileName, ValueType(date + " " + time, fSize));
        }
        return size*nmenb;
    }
    return 0;
}
